(function () {
  let _head = Symbol('_head');
  class ArrayList {
    constructor() {
      // 初始化一个头节点
      // this[_head] = new Node({val: null, next: null});
      Object.defineProperties(this, {
        [_head]: {
          writable: true,
          value: new Node({val: null, next: null}),
          enumerable: false, // 是否可枚举
          configurable: false // 不能删
        }
      });

      // 测试插入数据
    }

    update(val, index) {
      let findNode = this.find(index);
      findNode.val = val;
    }

    deleteByIndex(index) {
      let findNode = this.find(index);
      if (index === 0) {
        this[_head] = findNode.next;
        return;
      }
      let prevNode = this.find(index - 1);
      prevNode.next = findNode.next;

    }

    insert(val, index) {
      // 找到节点
      // 修改 找到节点的next 指向 new 节点
      // 修改 new 节点的next
      let newNode = new Node({val, next: null});
      if (!this[_head].val) {
        this[_head] = newNode;
        return
      }
      if (index === 0) {
        newNode.next = this[_head];
        this[_head] = newNode;
        return;
      }
      if (!index) {
        // 插入到最后一个
        let lastNode = this.find(this.size() - 1);
        console.log(this.size(), lastNode);
        lastNode.next = newNode;
        return;
      }
      //插入到中间位置
      let findElement = this.find(index - 1);
      newNode.next = findElement.next;
      findElement.next = newNode;
    }

    size() {
      let len = 0;
      let n = this[_head];
      while (n) {
        n = n.next;
        len++;
      }
      return len;
    }

    find(index) {
      let n = this[_head];
      let sum = 0;
      while (n && sum !== index) {
        n = n.next;
        sum++;
      }
      return n;
    }

    toString() {
      let str = '';
      let n = this[_head];
      while (n) {
        str += n.val;
        n = n.next;
        if (n) {
          str += ','
        }
      }
      return str;
    }

    toArray() {
      let arr = [];
      let n = this[_head];
      while (n) {
        arr.push(n.val);
        n = n.next;
      }
      return arr;
    }

  }

  // CommonJs Node
  // if (module && module.exports && exports) {
  //   module.exports = ArrayList;
  // } else {
  // 浏览器
  window.ArrayList = ArrayList;
  // }
})();
